/*
 * write_option.c
 *
 *  Created on: 2012/09/04
 *      Author: shenming
 */

#include <stdio.h>
#include "sqlite3.h"
#include "db_def.h"
#include "core.h"
#include "core_internal.h"
#include "Id.h"
#include "../../CCore/table/table.h"
#include "../../CCore/table/core_table.h"

/*TBL_OPTIONINFO*/
static INT insertOptionInfo(sqlite3 *db) {
	INT rc = 0;
	sqlite3_stmt * stmt;
	const char *zTail;
	PSZ sql_insert = NULL;
	BOOL bIsErr = FALSE;

	AST max = 0;
	AST i = 0;

	rc = sqlite3_exec(db, "begin;", 0, 0, 0);
	if (rc != SQLITE_OK) {
		return rc;
	}

	max = stCoreOptAccess.getMax();

	sql_insert = sqlite3_mprintf("INSERT INTO %q VALUES(?,?,?,?);",
			TBL_OPTIONINFO);
	rc = sqlite3_prepare(db, sql_insert, -1, &stmt, &zTail);
	if (rc != SQLITE_OK || stmt == NULL ) {
		if (sql_insert != NULL ) {
			sqlite3_free(sql_insert);
		}
		if (stmt != NULL ) {
			sqlite3_finalize(stmt);
		}
		return COEXIT_ERROR;
	}

	for (i = 1; i <= max; i++) {
		sqlite3_bind_int(stmt, P_TABLE_INDEX, i);

		sqlite3_bind_int(stmt, OPT_KIND, stCoreOptAccess.optId.get(i));

		sqlite3_bind_int(stmt, OPT_INT_VALUE, stCoreOptAccess.intValue.get(i));

		sqlite3_bind_text(stmt, OPT_STR_VALUE, stCoreOptAccess.strValue.get(i),
				-1, SQLITE_STATIC );

		rc = sqlite3_step(stmt);
		if (rc != SQLITE_DONE) {
			bIsErr = TRUE;
			printf("%s", sqlite3_errmsg(db));
			break;
		}
		sqlite3_reset(stmt);
	}

	if (bIsErr) {
		rc = sqlite3_exec(db, "rollback;", 0, 0, 0);
	} else {
		rc = sqlite3_exec(db, "commit;", 0, 0, 0);
	}

	if (sql_insert != NULL ) {
		sqlite3_free(sql_insert);
	}
	if (stmt != NULL ) {
		rc = sqlite3_finalize(stmt);
	}
	return rc;
}

INT DLL_EXPORT insertOption(sqlite3 *db) {
	INT rc = 0;
	rc = insertOptionInfo(db);
	if (rc != COEXIT_SUCCESS) {
		return rc;
	}
	return COEXIT_SUCCESS;
}
